package com.cpone.cloudweb.utils.bak;

import java.security.MessageDigest;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESCoder {
	
	public final String KEY_SHA = "SHA";
	public final String KEY_MD5 = "MD5";
	public final String KEY_MAC = "HmacMD5";
	/* BASE64���� */
	public String encryptBASE64(byte[] key) throws Exception{
		return (new BASE64Encoder()).encodeBuffer(key);
	}
	/* BASE64���� */
	public byte[] decryptBASE64(String key) throws Exception{
		return (new BASE64Decoder()).decodeBuffer(key);
	}
	/* MD5���� */
	@SuppressWarnings("unused")
	private byte[] encryptMd5(byte[] key) throws Exception{
		MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
		md5.update(key);
		return md5.digest();
	}
	/* SHA���� */
	@SuppressWarnings("unused")
	public byte[] encryptSHA(byte[] key) throws Exception{
		MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
		sha.update(key);
		return sha.digest();
	}
	/* ��ʼ��HMAC��Կ */
	public String initMacKey() throws Exception{
		KeyGenerator keyGen = KeyGenerator.getInstance(KEY_MAC);
		SecretKey secretKey = keyGen.generateKey();
		return encryptBASE64(secretKey.getEncoded());
	}
	/* HMAC���� */
	public byte[] encryptHMAC(byte[] data, String key) throws Exception{
		SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
		Mac mac = Mac.getInstance(secretKey.getAlgorithm());
		mac.init(secretKey);
		return mac.doFinal(data);
	}
	
	public String byteToString(byte[] bas){
		String str = "";
		for(int i=0; i<bas.length; i++){
			str += bas[i];
		}
		return str;
	}
	
	
}


